package com.atlin.project.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;

@Component
public class MailUtil {

    @Value("spring.mail")
    private String sender;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    TemplateEngine templateEngine;

    public static final String tempTemplateName = "regmail.html";


    //发送html内容的邮件,使用thymeleaf渲染页面
    public void sendHtmlMail(String from, String to, HashMap<String, String> content) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("数据异常告警信息");
        helper.setFrom(from);
        helper.setTo(to);

        helper.setSentDate(new Date());
        //生成邮件模板上的内容
        Context context = new Context();
        if (content != null && content.size() > 0) {
            for (String key : content.keySet()) {
                context.setVariable(key, content.get(key));
            }
        }
        String process = templateEngine.process(tempTemplateName, context);
        helper.setText(process, true);
        javaMailSender.send(mimeMessage);
    }
}